/*
 * @Author: SingleBiu
 * @Date: 2025-10-28 21:59:33
 * @LastEditors: SingleBiu
 * @LastEditTime: 2025-10-29 20:03:23
 * @Description: file content
 */
document.addEventListener('DOMContentLoaded', function() {
    // 登录表单提交
    const loginForm = document.getElementById('loginForm');
    if (loginForm) {
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const id = document.getElementById('id').value;
            const name = document.getElementById('name').value;
            
            if (!id || !name) {
                alert('请填写ID和姓名');
                return;
            }
            
            this.submit();
        });
    }
    
    // 加载用户列表
    loadUsers();
});

function loadUsers() {
    const usersTable = document.getElementById('usersTable');
    if (!usersTable) return;
    
    const tbody = usersTable.querySelector('tbody');
    tbody.innerHTML = '<tr><td colspan="2" class="loading">加载中...</td></tr>';
    
    fetch('/api/users')
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            return response.json();
        })
        .then(data => {
            if (data.error) {
                tbody.innerHTML = `<tr><td colspan="2" class="error">错误: ${data.error}</td></tr>`;
                return;
            }
            
            if (data.users && data.users.length > 0) {
                tbody.innerHTML = '';
                data.users.forEach(user => {
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${escapeHtml(user.id)}</td>
                        <td>${escapeHtml(user.name)}</td>
                    `;
                    tbody.appendChild(row);
                });
            } else {
                tbody.innerHTML = '<tr><td colspan="2" class="loading">暂无用户数据</td></tr>';
            }
        })
        .catch(error => {
            console.error('Error loading users:', error);
            tbody.innerHTML = `<tr><td colspan="2" class="error">加载失败: ${error.message}</td></tr>`;
        });
}

function escapeHtml(unsafe) {
    return unsafe
        .toString()
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
}